package com.zls.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.zls.client.UserClient;
import com.zls.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Controller
@RequestMapping("consumer/user")
@DefaultProperties(defaultFallback = "fallBackMethod")// 指定一个类的全局熔断方法
public class UserController {

//    @Autowired
//    private RestTemplate restTemplate;
    //    @Autowired
//    private DiscoveryClient discoveryClient; // eureka客户端，可以获取到eureka中服务的信息
    @Autowired
    private UserClient userClient;


    //    @HystrixCommand(fallbackMethod = "queryUserByIdFallBack")//用来声明一个降级逻辑的方法
//    @HystrixCommand//标记该方法需要熔断
    @ResponseBody
    @RequestMapping
    public User queryUserById(@RequestParam("id") int id) {
       /* // 根据服务名称，获取服务实例。有可能是集群，所以是service实例集合
        List<ServiceInstance> instances = discoveryClient.getInstances("service-provider");
        // 因为只有一个Service-provider。所以获取第一个实例
        ServiceInstance instance = instances.get(0);
        // 获取ip和端口信息，拼接成服务地址
        String baseUrl = "http://" + instance.getHost() + ":" + instance.getPort() + "/user/" + id;
        User user = this.restTemplate.getForObject(baseUrl, User.class);
        return user;*/
//        if(id == 1){
//            throw new RuntimeException("太忙了");
//        }
        // 通过client获取服务提供方的服务列表，这里我们只有一个
        /*String baseUrl = "http://service-provider/user/" + id;
        User user = this.restTemplate.getForObject(baseUrl, User.class);
        return user;*/
        User user = this.userClient.queryById(id);
        return user;
    }

    /**
     * 熔断方法
     * 返回值要和被熔断的方法的返回值一致
     * 熔断方法不需要参数
     *
     * @return
     */
    public User fallBackMethod() {
        User user = new User();
        user.setUsername("请求繁忙，请稍后再试！");
        return user;
    }

    public User queryUserByIdFallBack(int id) {
        User user = new User();
        user.setUsername("请求繁忙，请稍后再试！");
        return user;
    }

}
